import requestFormRepository from '@/repositories/requestForm'
import dateHelper from '@/common/js/dateHelper'
import moment from 'moment'

const createSubmissionForm = async (formData) => {
  return await requestFormRepository.createSubmissionForm(formData)
}

const updateRequestForm = async (formData) => {
  return await requestFormRepository.updateRequestForm(formData)
}

const searchSubmissionForm = async (refNo) => {
  return await requestFormRepository.searchSubmissionForm(refNo)
}

const getRequestFormWithCondition = async (param) => {
  let result = await requestFormRepository.getRequestFormWithCondition(param)
  let tableData = []
  result.content.map((item) => {
    let {expectedDate, expectedTime, firstVerifier, firstCoordinator, hasMore2ndVerifier, hasMoreFirstVerifier, secondVerifier, coordinator, verificationDeadling, requestprocedures} = item
    let verifier = ''
    if (hasMoreFirstVerifier === 'No') {
      verifier += firstVerifier
    } else {
      verifier += firstCoordinator
    }
    verifier += '; '
    if (hasMore2ndVerifier === 'No') {
      verifier += secondVerifier
    } else {
      verifier += coordinator
    }

    let executors = ''
    requestprocedures.forEach((procedure, index) => {
      executors += procedure.handledBy + '; '
    })

    item.executors = executors
    item.verificationDate = dateHelper.formatDate(verificationDeadling, 'DD-MMM-YYYY hh:ss')
    item.scheduleDateTime = dateHelper.formatDate(moment(expectedDate).add({hours: expectedTime.split(';')[0], minutes: expectedTime.split(';')[1]}).toDate(), 'DD-MMM-YYYY hh:ss')
    item.verifier = verifier
    return item
  })
  result.tableData = tableData
  return result
}

export default {
  getRequestFormWithCondition: getRequestFormWithCondition,
  createSubmissionForm: createSubmissionForm,
  searchSubmissionForm: searchSubmissionForm,
  updateRequestForm: updateRequestForm
}
